package com.wman.a17_thread_interaction;

/**
 * thread.stop();//不可预期的停止
 * thread.interrupt();中断线程，中断标记设置为true，目标线程去配合这个状态Thread.interrupted()进行相关处理
 * Thread.interrupted()返回中断状态并重置状态;isInterrupted()只返回状态，不重置
 * <p>
 * Thread.sleep为什么要try：睡眠过程中，外部调用了interrupt，
 */
public class ThreadInteractionDemo implements TestDemo {
    @Override
    public void runTest() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 1_000_000; i++) {
                    if (Thread.interrupted()) {
                        // 收尾
                        return;
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        // 这里捕获异常后，中断状态也会重置
                        // 收尾
                        return;
                    }
                    System.out.println("number:" + i);
                }
            }
        };
        thread.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        thread.stop();//不可预期的停止
        thread.interrupt();
    }
}
